import React, { useEffect, useState } from "react"
import { Avatar, Badge, Button, Form, Icon, Image, Input, Message, Modal, Progress, Select, Trigger, Upload } from "@arco-design/web-react"
import { useLocation, useNavigate } from 'react-router-dom';
import { useDispatch, useSelector } from "react-redux";
import { UserInfo } from "../../../domain/user";
import { updateMenusNum } from "../../../store/features/menus";
import { Popup, Textarea } from "@arco-design/mobile-react";
import { Blurhash } from "react-blurhash";
import { IconCamera, IconClose, IconCloseCircleFill, IconDelete, IconEdit, IconMore, IconPlus, IconStop } from "@arco-design/web-react/icon";
import FormItem from "@arco-design/web-react/es/Form/form-item";
import { LeoAvatar } from "../../../components/leo_Avatar";
import IMSDK from '../../../sdk'
import http, { getFile } from "../../../http";
import uuid from "../../../sdk/module/uuid";
import { uploadFile } from "../../chat/util/upload";
import { refreshUserInfo } from "../../../store/features/user";

const Option = Select.Option;



export interface Menu {
    name: string,
    type: string,
    path: string,
    num: number
}

export const ChatSidebar: React.FC<{ hook: { menus: Menu[], onTap: Function, current: number } }> = ({ hook }) => {
    const { menus, onTap, current } = hook;
    const [form] = Form.useForm();

    const [visibleInfo, setVisibleInfo] = useState(false);
    const IconFont = Icon.addFromIconFontCn({ src: '//at.alicdn.com/t/c/font_4634809_iex566rybui.js' });
    const { list } = useSelector((state: any) => state.conversation.value);
    const dispatch = useDispatch();
    const [file, setFile] = useState<any>();
    const cs = `overflow-hidden rounded-2xl arco-upload-list-item${file && file.status === 'error' ? ' is-error' : ''}`;

    useEffect(() => {
        if (list.length > 0) {
            const unReadCount = list.reduce((prev: any, curr: any) => prev + curr.unreadCount, 0)
            dispatch(updateMenusNum({ name: "聊天", num: `${unReadCount}` }));
        }
    }, [list])

    const options = [
        {
            label: '男生',
            value: 'MALE',
        },
        {
            label: '女生',
            value: "FEMALE",
        },
        {
            label: '保密',
            value: 'OTHER',
        },
    ]

    const handleClick = (index: number) => {
        onTap(index);
    }

    const { user } = useSelector((state: any) => {
        return state.user.value;
    })

    useEffect(() => {

    }, [user])

    return <div className='w-[70px] border-r border-r-[#E6EBF5] flex flex-col items-center relative'>

        <Modal
            className="w-[350px]"
            title={null}
            footer={null}
            closable={false}
            visible={visibleInfo}
            maskClosable={false}
            onOk={() => setVisibleInfo(false)}
            onCancel={() => setVisibleInfo(false)}
            autoFocus={false}
            focusLock={true}
        >
            <div className="mt-5 px-7">

                <div className="mb-4 text-[16px]">修改个人信息</div>
                <Form
                    onSubmit={(values) => {
                        const fetchData = async () => {
                            const response = await http.post("/updateInfo", values);
                            dispatch(refreshUserInfo());
                        }
                        fetchData();
                        Message.success("修改成功");
                    }}
                    form={form}
                    initialValues={{
                        nickName: user.nickName,
                        gender: user.gender,
                        signature: user.signature ?? ""
                    }}>
                    <FormItem layout="horizontal" labelAlign="left" label='昵称' field='nickName'>
                        <Input placeholder='' />
                    </FormItem>

                    <FormItem layout="horizontal" labelAlign="left" label='性别' field='gender'>
                        <Select
                            placeholder='Select city'
                            style={{ width: 232 }}
                        >
                            {options.map((option, index) => (
                                <Option key={option.label + '1'} value={option.value}>
                                    {option.label}
                                </Option>
                            ))}
                        </Select>
                    </FormItem>

                    <FormItem layout="horizontal" labelAlign="left" label='签名' field='signature'>
                        <Input.TextArea placeholder='' maxLength={50} />
                    </FormItem>


                    <div className="mb-6 mt-3 text-center space-x-12">
                        <Button className='w-[100px]' onClick={() => setVisibleInfo(false)}>取消</Button>
                        <Button className='w-[100px]' onClick={() => {
                            setVisibleInfo(false);
                            console.log("from ---")
                            form.submit()

                        }} type="primary">保存</Button>
                    </div>
                </Form>
            </div>
        </Modal>

        <Trigger
            popup={() =>
                <div className="w-[300px] min-h-[265px] shadow-2xl  border border-gray-100 overflow-hidden rounded-xl  bg-white relative">
                    <div className="pb-6">
                        <Blurhash
                            className="absolute top-0"
                            hash="LEHV6nWB2yk8pyo0adR*.7kCMdnj"
                            width={300}
                            height={130}
                            resolutionX={32}
                            resolutionY={32}
                            punch={1}
                        />
                        <div className="px-[12px]">

                            <div className="flex flex-row  leading-[35px]  cursor-pointer" onClick={() => setVisibleInfo(true)}>
                                <div className="w-[70px] flex-shrink-0 text-left text-gray-400">昵称</div>
                                <div className="max-w-[210px] whitespace-break-spaces">
                                    <div className="cursor-pointer chat-group-name text-left" >
                                        <span className="group-name">{user.nickName}</span>
                                        <span className="edit-icon ml-1 text-blue-500"><IconEdit className="edit-icon" ></IconEdit></span>
                                    </div>
                                </div>
                            </div>
                            <div className="flex flex-row  leading-[35px]  cursor-pointer" onClick={() => setVisibleInfo(true)}>
                                <div className="w-[70px] flex-shrink-0 text-left text-gray-400">个性签名</div>
                                <div className="max-w-[210px] whitespace-break-spaces">
                                    <div className="cursor-pointer chat-group-name text-left line-clamp-2" >
                                        <span className="group-name ">{user.signature ? user.signature : "暂未设置"}</span>
                                        <span className="edit-icon ml-1 text-blue-500"><IconEdit className="edit-icon"></IconEdit></span>
                                    </div>
                                </div>
                            </div>
                            <div className="flex flex-row cursor-pointer mt-2">
                                <div className="w-[70px] flex-shrink-0 text-left text-gray-400">朋友圈</div>
                                <div className="max-w-[210px] whitespace-break-spaces">
                                    <div className="flex-1 flex flex-row space-x-2 cursor-pointer" onClick={() => {

                                    }}>
                                        <img
                                            width={40}
                                            src='//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp'
                                            alt='lamp'
                                        />
                                        <img
                                            width={40}
                                            src='//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp'
                                            alt='lamp'
                                        />
                                        <img
                                            width={40}
                                            src='//p1-arco.byteimg.com/tos-cn-i-uwbnlip3yd/a8c8cdb109cb051163646151a4a5083b.png~tplv-uwbnlip3yd-webp.webp'
                                            alt='lamp'
                                        />
                                    </div>
                                </div>
                            </div>


                        </div>
                    </div>


                    <div className="absolute top-1 w-[300px] text-center ">
                        <Upload
                            fileList={file ? [file] : []}
                            showUploadList={false}
                            customRequest={() => { }}
                            onChange={(_, currentFile: any) => {

                                const uploadAvatar = async () => {
                                    const strFileName: any = currentFile!.name;
                                    const fileExtension = strFileName.substring(strFileName.lastIndexOf('.'));
                                    let fileName = uuid.v1() + fileExtension;
                                    const state = await uploadFile(currentFile.originFile!, fileName);
                                    const avatarUrl = getFile(fileName);
                                    console.log(avatarUrl);
                                    const response = await http.post("/updateAvatar", { url: avatarUrl })
                                    dispatch(refreshUserInfo())
                                }

                                if (currentFile.status == "init") {
                                    uploadAvatar();
                                }


                                console.log("onChange");
                                console.log(currentFile);
                                setFile({
                                    ...currentFile,
                                    url: URL.createObjectURL(currentFile.originFile),
                                });
                            }}
                            onProgress={(currentFile) => {
                                setFile(currentFile);
                            }}
                        >
                            <div>
                                <div className={cs}>
                                    <div className='w-[80px] h-[80px] overflow-hidden'>
                                        {file && file.url ? (<img className="w-[80px] h-[80px]" src={file.url} />) : (
                                            <LeoAvatar size={80} userPortrait={user.userPortrait} userName={user.nickName} ></LeoAvatar>)}
                                        <div className='arco-upload-list-item-picture-mask'>
                                            <IconCamera></IconCamera>
                                        </div>
                                    </div>
                                </div>
                                
                            </div>

                        </Upload>

                        <div className="mt-[4px] text-white font-bold ">
                                    账号: {user.userName}
                                </div>
                    </div>
                </div>}
            trigger='click'
            position='right'
            popupAlign={{
                right: [10, 60],
            }}
        >

            <div className="mt-[30px]">
                <LeoAvatar userPortrait={user.userPortrait} userName={user.nickName} ></LeoAvatar>
            </div>
        </Trigger>


        <div className='flex flex-col space-y-9 mt-[40px]'>
            {
                menus.map((item, index) =>
                    <Badge
                        key={item.name}
                        count={item.num}
                        dot={item.name == '聊天' ? false : true}
                        dotStyle={item.name == '聊天' ? {} : { width: 10, height: 10 }}
                    >
                        <div
                            key={item.name}
                            onClick={() => handleClick(index)}
                            className={` cursor-pointer text-[14px] ${current == index ? 'text-[#3d98ff]' : 'text-[#999]'}`}>
                            <IconFont type={item.type} style={{ fontSize: "30px" }} />
                            <div className="mt-2">{item.name}</div>
                        </div></Badge>)
            }
        </div>

        <Trigger
            popup={() =>
                <div onClick={() => {

                }} className="cursor-pointer w-[100px] h-[45px] bg-white text-center leading-[45px] shadow-custom-xl rounded-lg overflow-hidden">
                    <IconStop />
                    <span className="ml-2">退出登录</span>
                </div>
            }

            position='right'
            popupAlign={{
                bottom: 8,
                right: 8,
            }}
        >
            <IconFont className=" cursor-pointer absolute bottom-16" type='icon-caidan' style={{ fontSize: "30px", color: '#333' }} />
        </Trigger>

    </div>

}